package com.gexin.controller.system;

import java.util.Date;

import com.gexin.common.WebConst;
import com.gexin.common.cache.CacheUtils;
import com.gexin.common.cache.RedisKeyConst;
import com.gexin.common.utils.DateUtil;
import com.gexin.common.utils.StringUtil;
import com.gexin.core.web.SystemBaseController;
import com.gexin.model.system.AdminLog;
import com.gexin.model.system.AdminUser;
import com.jfinal.aop.Clear;
import com.jfinal.ext.route.ControllerBind;

@ControllerBind(controllerKey = "/system/login", viewPath = "WEB-INF/system/")
public class LoginController extends SystemBaseController {
	public static final String login_key_time = "cache:login:key:";
	public static final String login_key = "login_key";
	// 登录页面
	@Clear
	public void index() {
		String go = getPara("go");
		String token = getCookie(login_key);
		AdminUser admin = getSessionAttr(WebConst.Session_SysUser);
		if (admin == null && StringUtil.isNotBlank(token)) {
			Integer userid = CacheUtils.get(login_key_time + token);// 缓存七天
			if (userid != null) {
				admin = AdminUser.dao.findById(userid);
				setSessionAttr(WebConst.Session_SysUser,admin);
			}
		}
		if (admin != null) {
			if (StringUtil.isNotBlank(go)) {
				redirect(go);
				return;
			} else {
				redirect("/system/index");
				return;
			}
		}
		setAttr("go", go);
		render("login.html");
	}

	// 登录进去
	@Clear
	public void post() {
		if (!validateCaptcha("code")) {
			fail("验证码错误！");
			return;
		}
		String remember = getPara("remember", "none");
		AdminUser admin = getBean(AdminUser.class, "admin");
		setAttr("admin", admin);
		admin = AdminUser.dao.login(admin.getUsername(), admin.getPassword());
		if (admin == null) {
			fail("用户或者用户名输入错误！");
		} else if (admin.getInt("state") == 1) {
			fail("您的账户已经被禁用，请联系管理员！");
		} else {
			AdminLog.dao.addLog(AdminLog.Log_Type.LOGIN,admin.getId(), String.format("用户名：%s,登录", admin.getUsername()));
			admin.setLastLoginTime(new Date());
			admin.update();
			setSessionAttr(WebConst.Session_SysUser, admin);
			setSessionAttr(WebConst.Session_SysUserId, admin.getId());// 设置用户ID
			if ("save_login".equals(remember)) {
				String token = StringUtil.generID();
				setCookie(login_key, token, 604800);// 缓存七天
				CacheUtils.set(login_key_time + token, admin.getId(), RedisKeyConst.day * 7);// 缓存七天
			}
			success();
		}
	}

	// 验证码
	@Clear
	public void code() {
		this.renderCaptcha();
	}

	// 退出
	public void out() {
		removeSessionAttr(WebConst.Session_SysUser);
		String  token    =getCookie(login_key);
		removeSessionAttr(login_key);
		CacheUtils.del(login_key_time + token);// 缓存七天
		redirect("/system/login/" + DateUtil.getTimestamp());
	}
}
